﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
public partial class admin_Accounting_Accounting : System.Web.UI.Page
{
    int nuevo = 0;
    rUser user;
  

    Table table;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["userid"] == null) { Response.Redirect("../Default.aspx"); }
        //permiso();
        if (!Page.IsPostBack)
        {
            nuevo = 0;
            int id = 0; RE_GenericBean banco = new RE_GenericBean();
            DataSet ds = DB.getBanks();

            

            llenarcb_bank(ds);
            llenarcb_companies();
            filldeposits();
            fillpaypal();
            Utility.fillclients(cb_client, "All");
            
        }   


         
    }

    private void llenarcb_companies()
    {
         
        try
        {
            
            DataSet dsc = (DataSet)(Session["companies"]);
            if (dsc == null) {
                Utility.setVariablesSession();
                dsc = (DataSet)(Session["companies"]);
            }
            if (dsc != null)
            {
                ListItem listitem0 = new ListItem();
                listitem0.Text = "All"; listitem0.Value = "All";
                cb_company.Items.Add(listitem0);

                for (int ii = 0; ii <= (dsc.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsc.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsc.Tables[0].Rows[ii][0].ToString();
                    cb_company.Items.Add(listitem);

                }

            }

        }
        catch (Exception ec)
        {
            Utility.writeError("WS getCompanies no devolvio companias " + ec.Message);
        }
    
    }
    private void fillOrders(string id)
    {
        rUser user = (rUser)Session["userid"];
        
        if (user != null)
        {
            DataSet dsorders = DB.GetOrderAccbyClient(user.getUsuarioId());

            if (dsorders != null)
            {
                int cont = dsorders.Tables[0].Rows.Count - 1;
               // lb_mensaje.Text = cont.ToString()+";";
                
                gv_order.DataSource = dsorders;
                gv_order.DataBind();
               

            }
        }
        
    }

    private void filldeposits()
    {
        ArrayList array = new ArrayList();
        DataSet dsyear = DB.getDeposits(1, array);
        TreeNode mainnode = new TreeNode("Years");
        for (int i = 0; i < dsyear.Tables[0].Rows.Count; i++)
        {
            TreeNode node = new TreeNode(dsyear.Tables[0].Rows[i][1].ToString());
            node.Text = dsyear.Tables[0].Rows[i][1].ToString();
            node.Value = dsyear.Tables[0].Rows[i][0].ToString();
            node.ImageUrl = "~/img/calendar.jpg";
            node.SelectAction = TreeNodeSelectAction.Expand;
            //agregando meses
            array = new ArrayList();
            array.Add(dsyear.Tables[0].Rows[i][1].ToString());
            DataSet dsmonth = DB.getDeposits(2, array);
            for (int j = 0; j < dsmonth.Tables[0].Rows.Count; j++)
            {
                TreeNode newnode = new TreeNode();
                newnode.Text = dsmonth.Tables[0].Rows[j][1].ToString();
                newnode.Value = dsmonth.Tables[0].Rows[j][2].ToString();
                // newnode.SelectAction = TreeNodeSelectAction.Expand;
                newnode.ImageUrl = "~/img/month.png";
                ArrayList array2 = new ArrayList();
                array2.Add(dsyear.Tables[0].Rows[i][1].ToString());
                array2.Add(dsmonth.Tables[0].Rows[j][2].ToString());
                DataSet dsdep = DB.getDeposits(3, array2);
                for (int k = 0; k < dsdep.Tables[0].Rows.Count; k++)
                {
                    TreeNode newnode2 = new TreeNode();
                    newnode2.Text = dsdep.Tables[0].Rows[k][1].ToString() + "<br>" + dsdep.Tables[0].Rows[k][5].ToString() + "<br>Amount: " + dsdep.Tables[0].Rows[k][3].ToString() + "<br>Orders: " + dsdep.Tables[0].Rows[k][4].ToString();
                    newnode2.Value = dsdep.Tables[0].Rows[k][0].ToString();
                    newnode2.ImageUrl = "~/img/Bankcheck.png";
                    newnode2.NavigateUrl = "detailDeposit.aspx?id=" + dsdep.Tables[0].Rows[k][0].ToString();
                    // newnode2.SelectAction = TreeNodeSelectAction.Expand;
                    newnode.ChildNodes.Add(newnode2);
                }


                node.ChildNodes.Add(newnode);
                node.CollapseAll();
            }
            mainnode.ImageUrl = "~/img/checklist.png";
            mainnode.ChildNodes.Add(node);

        }

        TreeView1.Nodes.Add(mainnode);
        TreeView1.CssClass = "item";
        TreeView1.NodeIndent=25;
        TreeView1.NodeStyle.NodeSpacing = 10;
    }

    private void fillpaypal()
    {
        ArrayList array = new ArrayList();
        DataSet dsyear = DB.getDepositsPay(1, array);
        TreeNode mainnode = new TreeNode("Years");
        for (int i = 0; i < dsyear.Tables[0].Rows.Count; i++)
        {
            TreeNode node = new TreeNode(dsyear.Tables[0].Rows[i][1].ToString());
            node.Text = dsyear.Tables[0].Rows[i][1].ToString();
            node.Value = dsyear.Tables[0].Rows[i][0].ToString();
            node.ImageUrl = "~/img/calendar.jpg";
            node.SelectAction = TreeNodeSelectAction.Expand;
            //agregando meses
            array = new ArrayList();
            array.Add(dsyear.Tables[0].Rows[i][1].ToString());
            DataSet dsmonth = DB.getDepositsPay(2, array);
            for (int j = 0; j < dsmonth.Tables[0].Rows.Count; j++)
            {
                TreeNode newnode = new TreeNode();
                newnode.Text = dsmonth.Tables[0].Rows[j][1].ToString();
                newnode.Value = dsmonth.Tables[0].Rows[j][2].ToString();
                // newnode.SelectAction = TreeNodeSelectAction.Expand;
                newnode.ImageUrl = "~/img/month.png";
                ArrayList array2 = new ArrayList();
                array2.Add(dsyear.Tables[0].Rows[i][1].ToString());
                array2.Add(dsmonth.Tables[0].Rows[j][2].ToString());
                DataSet dsdep = DB.getDepositsPay(3, array2);
                for (int k = 0; k < dsdep.Tables[0].Rows.Count; k++)
                {
                    TreeNode newnode2 = new TreeNode();

                    newnode2.Text = dsdep.Tables[0].Rows[k][1].ToString() + "<br>Amount: " + dsdep.Tables[0].Rows[k][3].ToString() + "<br>Orders: " + dsdep.Tables[0].Rows[k][4].ToString()+"<br>";
                    newnode2.Value = dsdep.Tables[0].Rows[k][0].ToString();
                    newnode2.ImageUrl = "~/img/paypal_gold.png";
                    
                    newnode2.NavigateUrl = "paypalDeposit.aspx?id=" + dsdep.Tables[0].Rows[k][0].ToString();
                    // newnode2.SelectAction = TreeNodeSelectAction.Expand;
                    newnode.ChildNodes.Add(newnode2);
                    
                }


                node.ChildNodes.Add(newnode);
                node.CollapseAll();
                
            }
            mainnode.ImageUrl = "~/img/checklist.png";
            mainnode.ChildNodes.Add(node);
            

        }
       
        TreeView2.Nodes.Add(mainnode);
        TreeView2.NodeIndent = 20;
        TreeView2.NodeStyle.NodeSpacing = 10;
        TreeView2.CssClass = "item";
        
    }

    protected void Page_Init(object sender, EventArgs e)
    {


        DataSet ds = DB.getBanks();
        if (ds != null)
        {

            Table tabla1 = crearTabla(ds, 1);
            //tabla1.Caption = "<table border='1' width='100%' border-style='groove' border-color:'#000000' cellpadding='0' cellspacing='0' class='letrabold' bgcolor='#9AC9F8'><tr><td>Business Account</td></tr></table>";
            tabla1.Caption = "  ";
            tabla1.CaptionAlign = TableCaptionAlign.Left;
            // PBank.Controls.Add(table);
            AjaxControlToolkit.AccordionPane ap = new AjaxControlToolkit.AccordionPane();
            ap.ID = "APBANK";
            Label lbank1 = new Label();
            lbank1.Text = "Business Account";
            ap.Controls[0].Controls.Add(lbank1);
            ap.Controls[1].Controls.Add(table);

            Session["tableBank1"] = tabla1;

            Table tabla2 = crearTabla(ds, 2);
            //tabla2.Caption = "<table border='2' border-style='groove' width='100%' cellpadding='0' cellspacing='0' class='letrabold' bgcolor='#9AC9F8' ><tr><td>Vendor Bank's</td></tr></table>";
            tabla2.Caption = "  ";
            tabla2.CaptionAlign = TableCaptionAlign.Left;
            AjaxControlToolkit.AccordionPane apv = new AjaxControlToolkit.AccordionPane();
            apv.ID = "APBANK2";
            Label lbank2 = new Label();
            lbank2.Text = "Vendor Bank's";
            apv.Controls[0].Controls.Add(lbank2);
            apv.Controls[1].Controls.Add(tabla2);
            acc.Panes.Add(ap);
            acc.Panes.Add(apv);
            // PBankVendor.Controls.Add(tabla2);
            Session["tableBank2"] = tabla2;
            restricted();
            permiso();
            fillOrders("");

        }
    }

    private void permiso()
    {
        
        long permisodet = 0;
        RE_GenericBean permi = new RE_GenericBean();
        user = (rUser)(Session["userid"]);
        if (user != null)
        {
            permi = Utility.getPermisobyRuser(user, 18);// pagina Accounting
            permisodet = permi.int64C1;
            if ((permisodet & 2) != 2) { PDeposit.Enabled = false; } //pestana checks
            if ((permisodet & 4) != 4) { PPaypal.Enabled = false; } //pestana Paypal
            if ((permisodet & 8) != 8) { PBanks.Enabled = false; } //pestana Banks
            if ((permisodet & 16) != 16) { PAdd.Enabled = false; } //pestana Add
            if ((permisodet & 32) != 32) { client.Enabled = false; } //panel client
            if ((permisodet & 64) != 64) { pemployee.Enabled = false; } //generate report bpophotos
            if ((permisodet & 128) != 128) { lnk_clientreport.Enabled = false; } //generate report client
        }
    }

    private void restricted()
    {
        
        long permisodet = 0;
        RE_GenericBean permi = new RE_GenericBean();
        user = (rUser)(Session["userid"]);
        if (user != null)
        {
            permi = Utility.getPermisobyRuser(user, 18);// pagina Accounting
            permisodet = permi.int64C2;
            if ((permisodet & 1) == 1) { Response.Redirect(Request.UrlReferrer.ToString()); }
            if ((permisodet & 2) != 2) { createTabPanel(PDeposit, TabContainer1, "Deposit"); } else { PDeposit.Visible = false; } //pestana checks
            if ((permisodet & 4) != 4) { createTabPanel(PPaypal, TabContainer1, "Paypal"); } else { PPaypal.Visible = false; }//pestana Paypal
            if ((permisodet & 8) != 8) { createTabPanel(PBanks, TabContainer1, "Banks"); } else { PBanks.Visible = false; }//pestana Banks
            if ((permisodet & 16) != 16) { createTabPanel(PAdd, TabContainer1, "Add"); } else { PAdd.Visible = false; } //pestana Add
            if ((permisodet & 32) != 32) { TabContainer1.Visible = false; } else { client.Visible = false; } //panel client solo visible para clientes
            if ((permisodet & 64) == 64) { pemployee.Visible = false; }  //generate bpo report
            if ((permisodet & 128) == 128) { lnk_clientreport.Visible = false; } //generate client report
        }
    }

    private void createTabPanel(Panel Panel, AjaxControlToolkit.TabContainer TabContainer1, string headertext)
    {
       
        AjaxControlToolkit.TabPanel tabpanel = new AjaxControlToolkit.TabPanel();
        tabpanel.ID = headertext; tabpanel.HeaderText = headertext;
        tabpanel.Controls.Add(Panel);
        TabContainer1.Tabs.Add(tabpanel);
        TabContainer1.Visible = true;
    }
    private void llenarcb_bank(DataSet ds)
    {
        if (ds != null)
        {
            ListItem li = new ListItem();
            li.Text = "Select One";
            li.Value = "0";

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                li = new ListItem();
                li.Value = ds.Tables[0].Rows[i][0].ToString();
                li.Text = ds.Tables[0].Rows[i][1].ToString();

            }
        }
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void lnk_edit_Click(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[1].Style.Add("display", "none");//id
            e.Row.Cells[3].Style.Add("display", "none");//type
        }
    }


    protected void bt_edit_click(object sender, ImageClickEventArgs e)
    {
        //ModalPopupExtender1.Show();
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Session["newdeposit"] = 1;


        Response.Redirect("detailDeposit.aspx");

    }

    protected void lnk_save_bank_Click(object sender, EventArgs e)
    {
        TabContainer1.ActiveTabIndex = 2;
        lb_error.Visible = false;
        if (validar())
        {
            int nuevo = 0;
            if (Session["newbank"] != null) nuevo = (int)Session["newbank"];
            if (nuevo == 0)
            {
                int id = 0;
                if (Request.QueryString["id"] != null) id = int.Parse(Request.QueryString["id"].ToString());
                string temp = tb_bank_name.Text;
                string image = "bankIcon.png";
                string ext = "png";
                if (File1.HasFile)
                {
                    image = File1.FileName.ToString(); ;

                    int p = image.LastIndexOf(".");
                    ext = image.Substring(p + 1);
                }
                else
                {
                    string temp2 = img_icon.ImageUrl.ToString().Replace("~/data/icons/", "");
                    int p = temp2.LastIndexOf(".");
                    ext = "";

                }
                int resp = DB.addBank(tb_bank_name.Text, id, cb_typebank.SelectedValue, ext, tb_bank_number.Text);
                if (resp != 0)
                {
                    guardarlogo(resp);
                }
            }
            else
            {

                int resp = DB.addBank(tb_bank_name.Text, 0, cb_typebank.SelectedValue, "", tb_bank_number.Text);
            }


            Response.Redirect("Accounting.aspx");
        }
        else {
            lb_error.Text = "Failed to save the bank, one or more items missing";
            lb_error.Visible = true;
        
        }
    }

    private void guardarlogo(int id)
    {


        if (File1.PostedFile != null)
        {
            try
            {


                string filename = File1.FileName;
                int p = filename.LastIndexOf(".");
                int pp = filename.Length;

                string ext = filename.Substring(p + 1);
                File1.PostedFile.SaveAs(Server.MapPath("~//data/icons//banks//bankIcon" + id + "." + ext));
                img_icon.ImageUrl = "~//data/icons//banks//bankIcon" + id + "." + ext;

            }
            catch (Exception ex)
            {
                lb_error.Visible = true;
                lb_error.Text = "Image Error.";

            }
        }


    }

    private Table crearTabla(DataSet ds, int type)
    {
        int cont = 0;
        table = new Table();
        table.Controls.Clear();
        table.HorizontalAlign = HorizontalAlign.Center;
        table.Width = 600;
        table.CssClass = "letraNegra14";
        table.Font.Bold = true;
        table.CellPadding = 0;
        table.CellSpacing = 0;
        TableRow row = new TableRow();
        row.Width = 150;

        for (int i = 1; i <= ds.Tables[0].Rows.Count; i++)
        {
            if (ds.Tables[0].Rows[i - 1][2].ToString().Equals(type.ToString()))
            {

                TableCell cell = new TableCell();
                cell.BorderStyle = BorderStyle.Solid;
                cell.BorderWidth = 0;
                cell.VerticalAlign = VerticalAlign.Top;
                Table tableint = new Table();
                tableint.CellPadding = 0;
                tableint.CellSpacing = 0;

                TableRow rowint = new TableRow();
                rowint.Height = 105;
                rowint.VerticalAlign = VerticalAlign.Top;

                TableCell cellimage = new TableCell();
                cellimage.Width = 150;
                cellimage.HorizontalAlign = HorizontalAlign.Center;

                TableRow rowint2 = new TableRow();
                TableCell celltitle = new TableCell();
                celltitle.Width = 150;


                ImageButton imaButton = new ImageButton();
                int id = int.Parse(ds.Tables[0].Rows[i - 1][0].ToString());
                imaButton.ID = "bt_" + id;
                imaButton.BorderWidth = 0;
                //  imaButton.Attributes.Add("onmouseout", "this.width='45'; ; this.height='45';");
                // imaButton.Attributes.Add("onmouseover", "this.width='60'; this.height='60';");
                imaButton.ImageUrl = "~/data/icons/banks/" + ds.Tables[0].Rows[i - 1][3].ToString();
                imaButton.Attributes.Add("width", "95");
                imaButton.Attributes.Add("heigth", "95");
                imaButton.Attributes.Add("runat", "server");
                imaButton.CssClass = "efectBank";
                imaButton.Width = 75;
                imaButton.Height = 75;
                imaButton.Click += new ImageClickEventHandler(imaButton_Click);




                cellimage.VerticalAlign = VerticalAlign.Top;
                cellimage.Controls.Add(imaButton);

                rowint.Cells.Add(cellimage);

                Label labelbank = new Label();
                labelbank.ID = "lb_" + i;
                labelbank.Text = ds.Tables[0].Rows[i - 1][1].ToString();
                labelbank.CssClass = "letracombo";
                celltitle.VerticalAlign = VerticalAlign.Top;

                celltitle.Controls.Add(labelbank);

                celltitle.HorizontalAlign = HorizontalAlign.Center;
                rowint2.Cells.Add(celltitle);

                tableint.Rows.Add(rowint);
                tableint.Rows.Add(rowint2);

                cell.Controls.Add(tableint);

                row.Cells.Add(cell);
                cont++;
                if (cont == 1)
                {
                    table.Rows.Add(row);
                }
                else if ((cont % 4) == 0)
                {
                    table.Rows.Add(row);
                    row.Width = 150;
                    row = new TableRow();



                }
                else
                {
                    table.Rows.Remove(row);
                    table.Rows.Add(row);
                }
            }
        }

        return table;

    }
    void imaButton_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton but = (ImageButton)sender;
        string[] temp = but.ID.Split('_');
        if (temp[1] != null)
        {
            Response.Redirect("~/admin/Accounting.aspx?id=" + temp[1]);
        }

    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {

    }
    protected void lnk_cancel_bank_Click(object sender, EventArgs e)
    {
        tb_bank_name.Text = "";
        cb_typebank.SelectedIndex = 0;

        img_icon.ImageUrl = "~/img/blank.png";
        Response.Redirect("Accounting.aspx");
    }
    protected void lnk_okcancel_Click(object sender, EventArgs e)
    {
        int id = 0;
        if (Request.QueryString["id"] != null) id = int.Parse(Request.QueryString["id"].ToString());
        int resp = DB.deleteBank(id);
        Response.Redirect("Accounting.aspx");
    }
    protected void lnk_cancelcancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("Accounting.aspx");
    }

    protected void img_blank_Click(object sender, ImageClickEventArgs e)
    {
        P_cancel.Visible = true;
        lb_namebank.Text = tb_bank_name.Text;
        P_cancel_ModalPopupExtender.Show();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TabContainer1.ActiveTabIndex = 2;
        Session["newbank"] = 1;
        tb_bank_name.Text = "";
        cb_typebank.SelectedIndex = 0;
        pnlEditBank_ModalPopupExtender.Show();


    }
    private bool validar()
    {
        bool result = false;
        if (!tb_bank_name.Text.Equals("") && !tb_bank_number.Text.Equals("") && cb_typebank.SelectedIndex != 0 && (File1.HasFile || !img_icon.ImageUrl.Equals("~/img/blank.png")))
        {
            result = true;
        }


        return result;
    }


    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        Session["newpaypaldeposit"] = 1;


        Response.Redirect("paypalDeposit.aspx");
    }
    
    protected void lnk_cancelcancel1_Click(object sender, EventArgs e)
    {

            tb_startdate.Text = "";
            tb_enddate.Text = "";
            cb_client.SelectedIndex = 0;

            preport_ModalPopupExtender.Hide();
       
       
    }
   
    protected void lnk_search_Click(object sender, EventArgs e)
    {
                Label3.Visible = false;
                if (cb_paid.SelectedIndex != 0)
                {
                    string where = ""; string period = ""; string style = "General"; string type = "N/A"; int paid = 1;
                    if (!tb_startdate.Text.Equals(""))
                    {
                        String[] fecha = tb_startdate.Text.Split('/');
                    
                        if (cb_paid.SelectedIndex == 2)
                        {
                            where = where + "    ( case when ([ORDER].ord_resubmitteddate is NULL  ) then CONVERT(varchar, [ORDER].ord_submitted_date,101)  ELSE CONVERT(varchar, [ORDER].ord_resubmitteddate,101) END >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "' ) ";

                        }
                        else
                        {
                            where = where + "   (CASE WHEN tbl_cheque.chk_date IS NULL THEN CONVERT(varchar, tbl_paypal_tran.pay_tran_date,101)  ELSE CONVERT(varchar, tbl_cheque.chk_date,101) END >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "' ) ";
                        }
                        period += tb_startdate.Text;
                    }
                    if (!tb_enddate.Text.Equals(""))
                    {
                        String[] fecha2 = tb_enddate.Text.Split('/');
                        if (!where.Equals("")) { where = where + " and "; }
                        if (cb_paid.SelectedIndex == 2)
                        {
                            where = where + "    ( case when ([ORDER].ord_resubmitteddate is NULL  ) then CONVERT(varchar, [ORDER].ord_submitted_date,101)  ELSE CONVERT(varchar, [ORDER].ord_resubmitteddate,101) END <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "' ) ";

                        }
                        else
                        {
                            where = where + "    (CASE WHEN tbl_cheque.chk_date IS NULL THEN CONVERT(varchar, tbl_paypal_tran.pay_tran_date,101)  ELSE CONVERT(varchar, tbl_cheque.chk_date,101) END <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "' ) ";
                        }
                        if (!period.Equals("")) { period += " - "; }
                        period += tb_enddate.Text;
                    }
                    if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != -1)
                    {
                        if (!where.Equals("")) { where = where + " and "; }
                        where += " [ORDER].client_id='" + cb_client.SelectedValue + "' ";
                        style = "Individual";

                    }
                    int typereport = 0;
                    if (cb_paid.SelectedIndex != 0 && cb_paid.SelectedIndex != -1)
                    {
                        if (cb_paid.SelectedIndex == 1) { if (!where.Equals("")) { where = where + " and "; } where += " ([ORDER].paid = 'YES' )"; typereport = 1; type = "Paid Orders"; }
                        if (cb_paid.SelectedIndex == 2) { if (!where.Equals("")) { where = where + " and "; } where += " ([ORDER].paid is null or [ORDER].paid = 'NO' )"; paid = 0; typereport = 2; type = "No Paid Orders"; }
                    }
                    if (cb_company.SelectedIndex != 0 && cb_company.SelectedIndex != -1)
                    {
                        if (!where.Equals("")) { where = where + " and "; } where += " ([ORDER].company = "+cb_company.SelectedValue+" )"; 
                       
                    }
                    REPORTDS ds= null;
                    if (typereport == 1)
                    {
                        
                        ds = DB.getAccountReport(where, period, type, style, paid);
                        Session["ReportAccDsType"] = 1;
                    }

                    if (typereport == 2) {
                        ds = DB.getAccountReportNP(where, period, type, style, paid);
                        Session["ReportAccDsType"] = 2;
                    
                    }

                    if (ds != null)
                    {

                        Session["ReportAccDs"] = ds;
                        preport_ModalPopupExtender.Hide();
                        Response.Write("<script type='text/javascript'>window.open('AccountReport.aspx','cal','width=1000,height=800,left=150,top=2000,scrollbars=YES,resizable=YES');</script>");


                    }

                }
                else {
                    Label3.Text = "Please select a criteria [Paid Yes/No] ";
                    Label3.Visible = true;
                    preport_ModalPopupExtender.Show();
                
                }
    }

    protected void lnk_searchcl_Click(object sender, EventArgs e)
    {
        string ordersgroup = tb_orders.Text.Trim();

        ordersgroup = ordersgroup.Replace(",", "','");
        ordersgroup = "'" + ordersgroup + "'";
        ordersgroup = "and ordernum in (" + ordersgroup + ")";

        //ordersgroup = ordersgroup + " and ([ORDER].status_id = 3 or [ORDER].status_id = 4 or [ORDER].status_id = 5)";
              rUser ruser = (rUser)Session["userid"];
         RE_GenericBean permi = Utility.getPermisobyRuser(ruser, 1);
         RE_GenericBean permi2 = Utility.getPermisobyRuser(ruser, 6);
                  
                        DataSet ds = DB.GetOrdersAccCli(permi.int64C1, permi2.int64C1, ruser.getAlias(), ordersgroup, "", "", 1, 0);
                        //ds = DB.GetOrdersAcc(31, 31, "LB", where1, "", "", 1, perfilID);

                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            Panel2.Visible = true;
                            lnk_Assign.Enabled = true;
                            Session["masivo"] = null;
                            gv_multiple.DataSource = ds;
                            gv_multiple.DataBind();
                        }
     
    }
    protected void gv_multiple_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox isPaid = (TextBox)e.Row.FindControl("isPaid");
            string paid = isPaid.Text;
            if (paid == "false")
            {
                e.Row.FindControl("image").Visible = false;
            }
            e.Row.FindControl("isPaid").Visible = false;
        }

    }
    protected void editdetail(object sender, EventArgs e)
    {
        int index = 0;

        ImageButton bt = (ImageButton)sender;
        bt.Visible = false;
        GridViewRow objFila = (GridViewRow)bt.Parent.Parent;
        ImageButton btedit = (ImageButton)objFila.FindControl("bt_savedetail");
        btedit.Visible = true;

        index = objFila.RowIndex;
        int i = 0;




        foreach (GridViewRow ROW in gv_order.Rows)
        {
            if (i == index)
            {
                int con = ROW.Controls.Count;
                TextBox tb = (TextBox)ROW.FindControl("tbx_psffee");
                CheckBox chk = (CheckBox)ROW.FindControl("CHBX3");
                Image img = (Image)ROW.FindControl("image");
                if (img.Visible) { chk.Checked = true; }
                img.Visible = false;
                chk.Visible = true;
                chk.Enabled = true;
                tb.Enabled = true;


            }

            i++;
        }
    }
    protected void gvd_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        lb_error.Visible = false; lb_mensaje.Visible = false;
        if (e.CommandName == "Edit")
        {
            int index = Convert.ToInt32(e.CommandArgument);

            int i = 0;
            Control c = (Control)sender;



            foreach (GridViewRow ROW in gv_order.Rows)
            {
                if (i == index)
                {
                    int con = ROW.Controls.Count;
                    TextBox tb = (TextBox)ROW.FindControl("tbx_fee");
                    CheckBox chk = (CheckBox)ROW.FindControl("CHBX3");
                    Image img = (Image)ROW.FindControl("image");
                    Button bt = (Button)ROW.FindControl("bt_savedetail");
                    bt.Visible = true;
                    img.Visible = false;
                    chk.Visible = true;
                    chk.Enabled = true;
                    tb.Enabled = true;


                }

                i++;
            }

        }
        if (e.CommandName == "Save")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int i = 0;

            ArrayList array = new ArrayList();
            ArrayList arrayno = new ArrayList();
            foreach (GridViewRow ROW in gv_order.Rows)
            {
                if (i == index)
                {
                    int con = ROW.Controls.Count;
                    TextBox tb = (TextBox)ROW.FindControl("tbx_psffee");
                    CheckBox chk = (CheckBox)ROW.FindControl("CHBX3");
                    string ordernum = "";
                    string fee = "";
                    Label label = (Label)ROW.FindControl("lb_order");
                    if (label != null)
                    {
                        ordernum = label.Text;

                    }

                    if (!tb.Text.Equals(""))
                    {
                        fee = tb.Text;
                    }
                    if (chk.Checked)
                    {


                        RE_GenericBean rg = new RE_GenericBean();
                        rg.strC1 = ordernum;
                        rg.strC2 = fee;
                        //rg.strC3 = tb_id.Text;
                        array.Add(rg);
                        chk.Enabled = false;
                        chk.Visible = false;
                        tb.Enabled = false;
                    }
                    else
                    {

                        RE_GenericBean rg = new RE_GenericBean();
                        rg.strC1 = ordernum;
                        rg.strC2 = fee;
                        //rg.strC3 = tb_id.Text;
                        arrayno.Add(rg);
                        chk.Enabled = false;
                        chk.Visible = false;
                        tb.Enabled = false;

                    }



                }

                i++;
            }

            RE_GenericBean resop = new RE_GenericBean();

            if (array.Count > 0) { resop = DB.setPaidClient(array, ""); }
           // if (arrayno.Count > 0) { resop = DB.setUnPaidClient(arrayno, ""); }
            if (resop.intC1 == 1)
            {
                lb_mensaje.Text = "Change applied";
                lb_mensaje.Visible = true;

                fillOrders("");


            }
            else
            {
                lb_error.Text = "Change not applied:  " + resop.strC1;
                lb_error.Visible = true;
                fillOrders("");

            }

        }
    }
    protected void gv_order_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {

           
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
            }
        }
        

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chk = (CheckBox)e.Row.FindControl("CHBX3");
                TextBox isPaid = (TextBox)e.Row.FindControl("isPaid");
                Image img = (Image)e.Row.FindControl("image");
               
                string paid = isPaid.Text;
                if (paid == "false")
                {

                    chk.Checked = false;
                    img.Visible = false;
                }
                else
                {
                    chk.Checked = true;
                    img.Visible = true;
                }
                e.Row.FindControl("isPaid").Visible = false;
            }

        
    }
    protected void gv_order_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }

    protected void savedetail(object sender, EventArgs e)
    {
        int index = 0;
        ImageButton bt = (ImageButton)sender;
        GridViewRow objFila = (GridViewRow)bt.Parent.Parent;
        ImageButton btedit = (ImageButton)objFila.FindControl("bt_editdetail");
        btedit.Visible = false;

        index = objFila.RowIndex;


        int i = 0;

        ArrayList array = new ArrayList();
        ArrayList arrayno = new ArrayList();
        foreach (GridViewRow ROW in gv_order.Rows)
        {
            if (i == index)
            {
                int con = ROW.Controls.Count;
                TextBox tb = (TextBox)ROW.FindControl("tbx_psffee");
                ImageButton bt2 = (ImageButton)ROW.FindControl("bt_savedetail");
                bt2.Visible = false;

                CheckBox chk = (CheckBox)ROW.FindControl("CHBX3");
                string ordernum = "";
                string fee = "";
                Label label = (Label)ROW.FindControl("lb_order");
                if (label != null)
                {
                    ordernum = label.Text;

                }

                if (!tb.Text.Equals(""))
                {
                    fee = tb.Text;
                }
                if (chk.Checked)
                {


                    RE_GenericBean rg = new RE_GenericBean();
                    rg.strC1 = ordernum;
                    rg.strC2 = fee;
                  //  rg.strC3 = tb_id.Text;
                    array.Add(rg);
                    chk.Enabled = false;
                    chk.Visible = false;
                    tb.Enabled = false;
                }
                else
                {

                    RE_GenericBean rg = new RE_GenericBean();
                    rg.strC1 = ordernum;
                    rg.strC2 = fee;
                    //rg.strC3 = tb_id.Text;
                    arrayno.Add(rg);
                    chk.Enabled = false;
                    chk.Visible = false;
                    tb.Enabled = false;

                }



            }

            i++;
        }

        RE_GenericBean resop = new RE_GenericBean();

        if (array.Count > 0) { resop = DB.setPaidClient(array, ""); }
        if (arrayno.Count > 0) { resop = DB.setUnPaidClient(arrayno, ""); }
        if (resop.intC1 == 1)
        {
            //lb_mensaje.Text = "Change applied";
            //lb_mensaje.Visible = true;
            fillOrders("");


        }
        else
        {
            lb_error.Text = "Change not applied:  " + resop.strC1;
            lb_error.Visible = true;
            fillOrders("");

        }

    }

    

    protected void lnk_Assign_Click(object sender, EventArgs e)
    {
        Utility.setVariablesSession();
        lb_error.Visible = false; lb_mensaje.Visible = false;
        string ordersgroup = ""; int p = 0; int pos = 0;
        ordersgroup = " Where order_id in (";
        string[] orders = new string[100];
        ArrayList array = new ArrayList();
        int cont = 0;
        foreach (GridViewRow ROW in gv_multiple.Rows)
        {

            string ordernum = ""; string fee = "0";

            CheckBox chk = (CheckBox)ROW.FindControl("CHBX1");
            if (chk.Checked)
            {
                Label label = (Label)ROW.FindControl("lb_order");
                if (label != null)
                {
                    ordernum = label.Text;
                    cont++;
                    if (cont != 1)
                    {
                        ordersgroup = ordersgroup + " , " + ordernum;
                    }
                    else
                    {
                        ordersgroup = ordersgroup + " " + ordernum + " ";
                    }
                }
                TextBox txt = (TextBox)ROW.FindControl("tbx_psfprice");
                if (!txt.Text.Equals(""))
                {
                    fee = txt.Text;
                }

                RE_GenericBean rg = new RE_GenericBean();
                rg.strC1 = ordernum;
                rg.strC2 = fee;
                //rg.strC3 = tb_id.Text;
                array.Add(rg);

            }

        }
        ordersgroup = ordersgroup + " ) ";
        rUser ruser = (rUser)Session["userid"];
        RE_GenericBean resop = DB.setPaidClient(array, ruser.getUsuarioId());
        


        if (resop.intC1 == 1)
        {
            lb_mensaje.Text = "Paid Set";
            lb_mensaje.Visible = true;
            Panel2.Visible = false;


        }
        else
        {
            lb_error.Text = "Paid not Set:  " + resop.strC1;
            lb_error.Visible = true;
            


        }






    }
   
    
    protected void lnk_search0_Click(object sender, EventArgs e)
    {
        Label3.Visible = false;
        if (cb_paidcl.SelectedIndex != 0)
        {
            string where = ""; string period = ""; string style = "General"; string type = "N/A"; int paid = 1;
            if (!tb_startdatecl.Text.Equals(""))
            {
                String[] fecha = tb_startdatecl.Text.Split('/');
                //if (!where.Equals("")) { where = where + " and "; }
                if (cb_paidcl.SelectedIndex == 2)
                {
                    where = where + "    ( case when ([ORDER].ord_resubmitteddate is NULL  ) then CONVERT(varchar, [ORDER].ord_submitted_date,101)  ELSE CONVERT(varchar, [ORDER].ord_resubmitteddate,101) END <='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "' ) ";

                }
                else
                {
                    where = where + "   (CONVERT(varchar, [ORDER].paid_client_date,101)   >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "' ) ";
                }
                period += tb_startdatecl.Text;
            }
            if (!tb_enddatecl.Text.Equals(""))
            {
                String[] fecha2 = tb_enddatecl.Text.Split('/');
                if (!where.Equals("")) { where = where + " and "; }
                if (cb_paidcl.SelectedIndex == 2)
                {
                    where = where + "    ( case when ([ORDER].ord_resubmitteddate is NULL  ) then CONVERT(varchar, [ORDER].ord_submitted_date,101)  ELSE CONVERT(varchar, [ORDER].ord_resubmitteddate,101) END <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "' ) ";

                }
                else
                {
                    where = where + "    (CONVERT(varchar, [ORDER].paid_client_date,101)   <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "' ) ";
                }
                if (!period.Equals("")) { period += " - "; }
                period += tb_enddatecl.Text;
            }
            if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != -1)
            {
                if (!where.Equals("")) { where = where + " and "; }
                rUser user= (rUser)Session["userid"];
                if (user != null)
                {
                    where += " [ORDER].client_id='" + user.getUsuarioId() + "' ";
                    style = "Individual";
                }

            }
            if (cb_paidcl.SelectedIndex != 0 && cb_paidcl.SelectedIndex != -1)
            {
                if (cb_paidcl.SelectedIndex == 1) { if (!where.Equals("")) { where = where + " and "; } where += " ([ORDER].paid_client = 'YES' )"; }
                if (cb_paidcl.SelectedIndex == 2) { if (!where.Equals("")) { where = where + " and "; } where += " ([ORDER].paid_client is null or [ORDER].paid_client = 'NO' )"; paid = 0; }
            }
            REPORTDS ds;
            ds = DB.getAccountReportCl(where, period, type, style, paid);
            if (ds != null)
            {
                Session["ReportAccDs"] = ds;
                Response.Write("<script type='text/javascript'>window.open('AccountReportClient.aspx','cal','width=1000,height=800,left=150,top=2000,scrollbars=YES,resizable=YES');</script>");
                preport_ModalPopupExtender.Hide();

            }
        }
        else
        {
            Label3.Text = "Please select a criteria [Paid Yes/No] ";
            Label3.Visible = true;
            preport_ModalPopupExtender.Show();

        }
    }
    protected void generatereport_Click(object sender, EventArgs e)
    {

    }
}